package es

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"month_zg5/book_srv/common/global"
	"month_zg5/book_srv/models"
	book_rpc "month_zg5/book_srv/proto"
	"strconv"
)

func CreateBookEs(index string, book *models.Book) error {
	_, err := global.EsClient.Index().Index(index).Id(strconv.Itoa(int(book.ID))).BodyJson(book).Do(context.Background())
	return err
}

// 高亮
func SearchBook(index string, query elastic.Query, high *elastic.Highlight) []*book_rpc.BookInfo {
	res, err := global.EsClient.Search().Index(index).Query(query).Highlight(high).Do(context.Background())
	if err != nil {
		return nil
	}
	var bookMaps []map[string]interface{}
	for _, v := range res.Hits.Hits {
		var bookMap map[string]interface{}
		json.Unmarshal(v.Source, &bookMap)
		for i, h := range v.Highlight {
			bookMap[i] = h[0]
		}
		bookMaps = append(bookMaps, bookMap)
	}
	var bookInfo []*book_rpc.BookInfo
	for _, bookMap := range bookMaps {
		var info = &book_rpc.BookInfo{
			Title:            bookMap["title"].(string),
			BookType:         int32(bookMap["book_type"].(float64)),
			Author:           bookMap["author"].(string),
			Content:          bookMap["content"].(string),
			NumberOfComments: int32(bookMap["number_of_comments"].(float64)),
			Readings:         int32(bookMap["readings"].(float64)),
		}
		bookInfo = append(bookInfo, info)
	}
	return bookInfo
}
